/*
 * Copyright (c) 2006-2019, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2017-07-24     Tanek        the first version
 * 2018-11-12     Ernest Chen  modify copyright
 */
 
#include <stdint.h>
#include <rthw.h>
#include <rtthread.h>
#include "gd32vf103.h"
#include "riscv_encoding.h"

#define TMR_MSIP 0xFFC
#define TMR_MSIP_size   0x4
#define TMR_MTIMECMP 0x8
#define TMR_MTIMECMP_size 0x8
#define TMR_MTIME 0x0
#define TMR_MTIME_size 0x8

#define TMR_CTRL_ADDR           0xd1000000
#define TMR_REG(offset)         _REG32(TMR_CTRL_ADDR, offset)
#define TMR_FREQ                ((uint32_t)SystemCoreClock/4)  //units HZ

#define _SCB_BASE       (0xE000E010UL)
#define _SYSTICK_CTRL   (*(rt_uint32_t *)(_SCB_BASE + 0x0))
#define _SYSTICK_LOAD   (*(rt_uint32_t *)(_SCB_BASE + 0x4))
#define _SYSTICK_VAL    (*(rt_uint32_t *)(_SCB_BASE + 0x8))
#define _SYSTICK_CALIB  (*(rt_uint32_t *)(_SCB_BASE + 0xC))
#define _SYSTICK_PRI    (*(rt_uint8_t  *)(0xE000ED23UL))


// Holds the system core clock, which is the system clock 
// frequency supplied to the SysTick timer and the processor 
// core clock.
extern uint32_t SystemCoreClock;


void riscv_clock_init(void)
{
	SystemInit();

	//ECLIT init
	eclic_init(ECLIC_NUM_INTERRUPTS);
	eclic_mode_enable();
	set_csr(mstatus, MSTATUS_MIE);
}

static void ostick_config(rt_uint32_t ticks)
{
	//set value
	*(rt_uint64_t *)(TMR_CTRL_ADDR + TMR_MTIMECMP) = ticks;
	//enable interrupt
	eclic_irq_enable(CLIC_INT_TMR, 0, 0);
}

void eclic_mtip_handler(void)
{
	// clear value
	*(rt_uint64_t *)(TMR_CTRL_ADDR + TMR_MTIME) = 0;
	// enter interrupt
	rt_interrupt_enter();
	// tick increase
	rt_tick_increase();

	// leave interrupt
	rt_interrupt_leave();
}


#if defined(RT_USING_USER_MAIN) && defined(RT_USING_HEAP)
#define RT_HEAP_SIZE 4096
static uint32_t rt_heap[RT_HEAP_SIZE];     // heap default size: 4K(1024 * 4)
RT_WEAK void *rt_heap_begin_get(void)
{
    return rt_heap;
}

RT_WEAK void *rt_heap_end_get(void)
{
    return rt_heap + RT_HEAP_SIZE;
}
#endif

extern void uart_init(void);
//extern int finsh_system_init(void);

/**
 * This function will initial your board.
 */
void rt_hw_board_init()
{
    riscv_clock_init();
    /* System Tick Configuration */
    ostick_config(TMR_FREQ / RT_TICK_PER_SECOND);

    uart_init();
    /* Call components board initial (use INIT_BOARD_EXPORT()) */
#ifdef RT_USING_COMPONENTS_INIT
    rt_components_board_init();
#endif

#if defined(RT_USING_USER_MAIN) && defined(RT_USING_HEAP)
    rt_system_heap_init(rt_heap_begin_get(), rt_heap_end_get());
#endif
}

void SysTick_Handler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    rt_tick_increase();

    /* leave interrupt */
    rt_interrupt_leave();
}
